package com.mayflygeek.mayflyask.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.mayflygeek.mayflyask.entity.User;
import com.mayflygeek.mayflyask.util.Constants;
import com.mayflygeek.mayflyask.util.UserUtils;
/**
 * @author 蝈蝈 
 * @email guodefu909@126.com
 * @team 蜉蝣极客
 * @link www.mayflygeek.com
 * 用户登录拦截器
 */
public class UserInterceptor extends HandlerInterceptorAdapter {

	private Logger log = LoggerFactory.getLogger(getClass());
	
	@Resource
	private HttpSession session;

	// 拦截前处理
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		User loginUser = (User) session.getAttribute(Constants.SESSION_USER);
		if (loginUser != null && loginUser.getId() != null) {
			log.debug("============================loginUser is not null!");
			UserUtils.setSessionUser(loginUser);
			if (loginUser.getRememberMe() != null && loginUser.getRememberMe()) {
				Cookie cookie = new Cookie("JSESSIONID", session.getId());
				cookie.setPath(request.getContextPath() + "/");
				cookie.setMaxAge(Constants.SESSION_MAX_AGE);// 单位秒
				response.addCookie(cookie);
			}
			return true;
		}
		log.debug("============================loginUser is null!");
		response.sendRedirect(request.getContextPath() + "/login/toLogin");
		return false;
	}

	// 拦截后处理
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mav)
			throws Exception {
		log.info("postHandle");
		super.postHandle(request, response, handler, mav);
	}
}